package com.leyou.user.service;

import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.utils.CodecUtils;
import com.leyou.utils.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 项目: leyou
 *
 * @author 岩冰
 * @version 2018/10/17 12:28
 */
@Service
public class UserService {
    @Resource
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    static final String KEY_PREFIX = "user:code:phone:";
    static final Logger logger = LoggerFactory.getLogger(UserService.class);

    public Boolean checkUserData(String data, Integer type) {

        if (StringUtils.isBlank(data) || type == null) {
            return null;
        }
        User user = new User();
        if (type == 1) {
            user.setUsername(data);

        } else if (type == 2) {
            user.setPhone(data);
        } else {
            return null;
        }
        return userMapper.selectCount(user) == 0;
    }

    public Boolean sendVerifyCode(String phone) {
        if (StringUtils.isBlank(phone)) {
            return null;
        }
        String code = NumberUtils.generateCode(6);
        try {
            HashMap<String, String> msg = new HashMap<>();
            msg.put("phone", phone);
            msg.put("code", code);
            amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", msg);
            redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
            return true;
        } catch (AmqpException e) {
            e.printStackTrace();
            logger.error("发送短信失败。phone：{}， code：{}", phone, code);
            return false;
        }
    }

    public Boolean register(User user, String code) {
        String key = KEY_PREFIX + user.getPhone();
        String redisCode = redisTemplate.opsForValue().get(key);
        if (code.equals(redisCode)) {
            //redis的验证码相同的话
            //先密码加密
            String salt = CodecUtils.generateSalt();
            user.setSalt(salt);
            user.setCreated(new Date());
            user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));
            //注册
           Boolean boll= this.userMapper.insert(user) == 1;
            if (boll) {
                try {
                    this.redisTemplate.delete(key);
                } catch (Exception e) {
                    logger.error("删除缓存验证码失败，code：{}", code, e);
                }
            }
            return boll;
        }
        return null;
    }


    /**
     * 根据用户名和密码查询用户信息是否正确
     * @param username
     * @param password
     * @return
     */
    public User queryUser(String username, String password) {
        if (StringUtils.isBlank(username)||StringUtils.isBlank(password)) {
            return null;
        }
        User recode = new User().setUsername(username);
        User user = this.userMapper.selectOne(recode);
        if (user==null) {
            return null;
        }
        if (CodecUtils.md5Hex(password, user.getSalt()).equals(user.getPassword())) {
            //如果密码一致的话,返回 user
            return user;
        }
        return null;
    }
}
